package com.youbug.mall.product_pms.controller;


import com.youbug.common.vo.R;
import com.youbug.mall.product_pms.entity.PmsCategory;
import com.youbug.mall.product_pms.service.ICategoryService;
import com.youbug.mall.product_pms.service.IPmsCategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 商品三级分类 前端控制器
 * </p>
 *
 * @author youbug
 * @since 2023-05-07
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IPmsCategoryBrandRelationService pmsCategoryBrandRelationService;
    /**
     * 查询出所有分类以及子分类，以树形结构组装起来列表
     */
    @RequestMapping("/list/tree")
    public R<List<PmsCategory>> list(){

        List<PmsCategory> entities = categoryService.listWithTree();

        return R.ok(entities);
    }

    @PostMapping("/add")
    public R<Boolean> add(@RequestBody PmsCategory category){

        boolean add = categoryService.addCategory(category);
        categoryService.cleanCache(add);
        return R.ok(add);
    }

    @PostMapping("/update")
    @Transactional(transactionManager = "transactionManagerPms", rollbackFor = Exception.class)
    public R<Boolean> update(@RequestBody PmsCategory category){

        boolean update = categoryService.updateById(category);
        pmsCategoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        categoryService.cleanCache(update);

        return R.ok(update);
    }

    @GetMapping("/delete/{id}")
    public R<Boolean> delete(@PathVariable Long id){

        boolean delete = categoryService.deleteById(id);
        categoryService.cleanCache(delete);
        return R.ok(delete);
    }

}

